package com.chen.auth.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: cgd
 * @description: 用来解决认证过的用户访问无权限资源时的异常
 * @date: 2022/3/31 14:00
 * @version: 1.0
 */
public class SimpleAccessDeniedHandler implements AccessDeniedHandler {
    /**
     * 自定义响应格式
     */
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws ServletException {
        Map map = new HashMap();
        map.put("message", "无权操作");
        map.put("path", httpServletRequest.getServletPath());
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(httpServletResponse.getOutputStream(), map);
        } catch (Exception ex) {
            throw new ServletException();
        }
    }
}
